var mongoose = require('mongoose');
var Product = require("../models/mod_product");
var rc4=require("../models/mod_password");

//新增
exports.product_create = function (req, res, next) {
    // req.body.author=JSON.parse(rc4(req.body.author));
    //解决特殊情况
    if(typeof(req.body.parameter)!="object"){
        req.body.parameter = JSON.parse(req.body.parameter);
    }
    const product = new Product(req.body);

    product.save().then((data) => {
        res.json(data);
    }).catch(err => res.json(err));
}
//修改
exports.product_update = function (req, res, next) {
    //解决特殊情况
    if(typeof(req.body.parameter)!="object"){
        req.body.parameter = JSON.parse(req.body.parameter);
    }
    const id = req.params.id;
    Product.findByIdAndUpdate(id, { $set: req.body }, { new: true }).then(data => {
        res.json(data);
    });
}
//删除一个
exports.product_delete = function (req, res, next) {
    const id = req.params.id;
    Product.findByIdAndDelete(id).then(data => {
        res.json(data);
    });
}
//删除多个
exports.product_removes = function (req, res, next) {
    const ids = req.body.ids.split(",");
    Product.remove({ _id: { $in: ids } }).then(data => {
        res.json(data);
    });
}
//查询指定数据
exports.product_list_id = function (req, res, next) {
    const id = req.params.id;
    Product.findById(id).then(data => {
        res.json(data);
    });
}
//查询所有数据---没限制
exports.product_lm = function (req, res, next) {
    Product.find().then(data => {
        res.json(data);
    });
}
//查询所有（分页）
exports.product_list = function (req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 10;
    var search = req.body.search ? req.body.search : '';
    var ids = req.body.ids ? req.body.ids : '';

    var options = {
        page: +page,
        limit: +rows,
        sort: { _id: -1 }
    }

    


    var queryparams={};
    if(req.body.search&&search.length>0){
        queryparams={
            $or: [
                {"name":new RegExp(search,'i')},
                {"source":new RegExp(search,'i')},
                {"keywords":{$elemMatch:{$eq:search}}}
            ]
        }
    }

    if(req.body.ids&&ids.length>0){
        const ids = req.body.ids.split(",");
        //深拷贝，条件叠加
        queryparams=Object.assign(queryparams,{
            product_type: { $in: ids }
        })
    }

    Product.paginate(queryparams, options, function (err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}